package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//异常方法处理的异常类
    public R handlerSqlException(SQLIntegrityConstraintViolationException e){
        //获取异常信息
        String msg = e.getMessage();
        //根据空格分割找出用户名
        String username = msg.split(" ")[2];
        //包含以下信息就返回错误信息
        if (msg.contains("Duplicate entry")){
            return R.error(username+"已存在");
        }
        return R.error("未知错误");

    }
    @ExceptionHandler(CustomException.class)//异常方法处理的异常类
    public R<String> exceptionHandler(CustomException ex) {
        log.info(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
